package controller

import (
	"encoding/json"
	"github.com/cyfqyb/fiber_demo/global"
	"github.com/cyfqyb/fiber_demo/models"
	"github.com/gofiber/fiber/v2"
)

func init() {
	RegisterRoute(func(app *fiber.App) {
		adminView := app.Group("/admin")
		adminView.Get("", admin)
		adminView.Post("/login", login)
	})
}

type adminDto struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

func admin(c *fiber.Ctx) error {
	users := []string{"cy", "blob", "john"}
	usersJson, _ := json.Marshal(users)
	return c.Render("index", fiber.Map{
		"Title":    "welcome to fqyb",
		"users":    users,
		"names":    string(usersJson),
		"Password": "123",
	})
}

func login(c *fiber.Ctx) error {
	var dto adminDto
	var user models.User
	if err := c.BodyParser(&dto); err != nil {
		return Fail(c, err.Error())
	}
	err := global.Db.Where(&models.User{Name: dto.Name, Password: dto.Password}).First(&user).Error
	if err != nil {
		return Fail(c, "用户名或密码错误")
	}
	return Success(c, dto)
}
